class InsertionSort {
    constructor() {
        this.numbers = [];
        this.isRunning = false;
        this.currentStep = 0;
        this.isAutoSorting = false;
        this.currentCard = null;
        
        this.initializeElements();
        this.bindEvents();
    }

    initializeElements() {
        this.container = document.getElementById('numbersContainer');
        this.currentStepDisplay = document.getElementById('currentStep');
        this.generateNewBtn = document.getElementById('generateNew');
        this.startSortBtn = document.getElementById('startSort');
        this.nextStepBtn = document.getElementById('nextStep');
        this.resetBtn = document.getElementById('reset');
    }

    bindEvents() {
        this.generateNewBtn.addEventListener('click', () => this.generateNumbers());
        this.startSortBtn.addEventListener('click', () => this.startSort());
        this.nextStepBtn.addEventListener('click', () => this.nextStep());
        this.resetBtn.addEventListener('click', () => this.reset());
    }

    generateNumbers() {
        this.numbers = [];
        for (let i = 0; i < 6; i++) {
            this.numbers.push(Math.floor(Math.random() * 99) + 1);
        }
        this.reset();
        this.renderNumbers();
    }

    renderNumbers() {
        this.container.innerHTML = '';
        this.numbers.forEach((num, index) => {
            const box = document.createElement('div');
            box.className = 'number-box';
            box.textContent = num;
            if (index <= this.currentStep) {
                box.classList.add('sorted');
            }
            this.container.appendChild(box);
        });
    }

    async startSort() {
        if (this.isRunning) return;
        this.isRunning = true;
        this.isAutoSorting = true;
        this.startSortBtn.disabled = true;
        this.generateNewBtn.disabled = true;
        this.nextStepBtn.disabled = true;

        for (let i = 1; i < this.numbers.length; i++) {
            await this.insertCard(i);
        }

        this.finishSort();
    }

    async insertCard(index) {
        const boxes = document.querySelectorAll('.number-box');
        const currentValue = this.numbers[index];
        let j = index - 1;

        // 拿起当前牌
        boxes[index].classList.add('current-card');
        this.currentStepDisplay.textContent = `拿起第 ${index + 1} 张牌: ${currentValue}`;
        await new Promise(resolve => setTimeout(resolve, 500));

        // 寻找插入位置
        while (j >= 0 && this.numbers[j] > currentValue) {
            boxes[j].classList.add('comparing');
            this.currentStepDisplay.textContent = 
                `比较 ${this.numbers[j]} 和 ${currentValue}`;
            await new Promise(resolve => setTimeout(resolve, 500));

            this.numbers[j + 1] = this.numbers[j];
            boxes[j].classList.remove('comparing');
            j--;
        }

        // 插入到正确位置
        this.numbers[j + 1] = currentValue;
        this.currentStep = index;
        this.renderNumbers();
        
        await new Promise(resolve => setTimeout(resolve, 500));
    }

    async nextStep() {
        if (this.isAutoSorting) return;

        if (!this.isRunning) {
            this.isRunning = true;
            this.startSortBtn.disabled = true;
            this.generateNewBtn.disabled = true;
            this.currentStep = 0;
        }

        if (this.currentStep < this.numbers.length - 1) {
            await this.insertCard(this.currentStep + 1);
        } else {
            this.finishSort();
        }
    }

    finishSort() {
        this.isRunning = false;
        this.isAutoSorting = false;
        this.startSortBtn.disabled = false;
        this.generateNewBtn.disabled = false;
        this.nextStepBtn.disabled = false;
        this.currentStepDisplay.textContent = '排序完成！';
        
        const boxes = document.querySelectorAll('.number-box');
        boxes.forEach(box => box.classList.add('sorted'));
    }

    reset() {
        this.currentStep = 0;
        this.isRunning = false;
        this.isAutoSorting = false;
        this.startSortBtn.disabled = false;
        this.generateNewBtn.disabled = false;
        this.nextStepBtn.disabled = false;
        this.currentStepDisplay.textContent = '准备开始...';
        this.renderNumbers();
    }
}

// 初始化
window.addEventListener('DOMContentLoaded', () => {
    const game = new InsertionSort();
    game.generateNumbers();
}); 